import json
from pprint import pformat

from flask import Blueprint, request
from loguru import logger

from app.error import AuthenticationError
from app.json_handlers import require_json
from app.response_handlers import success_api, fail_api

from app.extensions import api_client, analyzer, des_crypto
from app.utils.login import CASLoginStrategy
from app.utils.validation import (
    validate_required_fields,
    validate_file_upload,
    validate_tax_type,
    validate_tax_org_number
)
from app.services.excel_service import ExcelService
from app.utils.xmind_tools import XmindTools

bp = Blueprint("platform", __name__)


@bp.route("/sendData", methods=["POST"])
@require_json()
def send_data() -> dict:
    """发送中台加密数据"""
    encrypted_data = request.get_json()
    logger.info(f"request decrypt data = {pformat(encrypted_data)}")
    response = api_client.send_task_data(encrypted_data)
    message = des_crypto.decrypt(response)
    logger.info(f"response decrypt data = {pformat(message)}")
    return json.loads(message)


@bp.route("/compareExcelCells", methods=["POST"])
def compare_excel_cells() -> dict:
    """比对excel行列数据"""
    is_consistent, result = ExcelService.compare_excel_cells()
    if not is_consistent:
        return fail_api(result, msg="文件内容不一致")
    return success_api(msg="文件内容完全一致")


@bp.route("/callBack", methods=["GET", "POST"])
@require_json()
def call_back() -> dict:
    """透传数据"""
    json_data = request.get_data()
    json_data = json_data.decode("utf-8")
    json_data = json.loads(json_data)
    logger.error(f"preData/callback request data = {pformat(json_data)}")
    return json_data


@bp.route("/compareDownloadExcelFile", methods=["POST"])
@require_json()
def compare_download_excel_file() -> dict:
    """下载并比较Excel文件"""
    payload = validate_required_fields(
        request.get_json(), ["path","org_tax_num", "tax_type", "url", "cookie","declare_month"]
    )
    validate_tax_type(payload["tax_type"])
    validate_tax_org_number(payload["org_tax_num"])

    is_consistent, result = ExcelService.compare_download_excel_file(payload)
    if not is_consistent:
        return success_api(result, msg="文件内容不一致")
    return success_api(msg="文件内容完全一致")


@bp.route("/getCaseCount", methods=["POST"])
def get_case_count() -> dict:
    """计算用例数量"""
    files = validate_file_upload(required_count=1, allowed_extensions=[".xmind"])
    xmind_numbers = XmindTools(files[0], analyzer)
    return success_api(data=xmind_numbers.get_result())


@bp.route("/login", methods=["POST"])
def login() -> dict:
    """登录"""
    credentials = validate_required_fields(
        request.get_json(), ["username", "password", "env"]
    )
    auth_strategy = CASLoginStrategy(
        env=credentials["env"],
        username=credentials["username"],
        password=credentials["password"],
    )
    token = auth_strategy.authenticate()
    logger.info(f"Obtained token: {token}")
    if not token:
        raise AuthenticationError("用户名或密码错误", 401)
    return success_api(data=token, msg="登录成功")


@bp.route("/receiveXmlData", methods=["POST"])
def receive_xml_data() -> dict:
    """接收xml数据"""
    xml_data = request.get_data(as_text=True)
    logger.info(f"xml_data : {xml_data }")
    return success_api(data=xml_data, msg="接收成功")
